package com.titanrise.crm.config;

import com.titanrise.crm.environment.annotation.Component;

import java.util.concurrent.*;
/**
 * @Description:
 * @Author: pront
 * @Time:2024-11-20 21:55
 */
@Component
public class ThreadPoolConfig {

    // 线程池实例
    private final ThreadPoolExecutor threadPoolExecutor;

    // 构造方法：初始化线程池
    public ThreadPoolConfig() {
        int corePoolSize = 10;               // 核心线程数
        int maximumPoolSize = 50;           // 最大线程数
        long keepAliveTime = 60L;           // 空闲线程存活时间（秒）
        TimeUnit timeUnit = TimeUnit.SECONDS; // 时间单位
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(100); // 任务队列

        // 创建线程池
        this.threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                timeUnit,
                workQueue,
                new ThreadFactory() { // 自定义线程工厂（可选）
                    private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = defaultFactory.newThread(r);
                        thread.setName("custom-thread-" + thread.getId());
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );
    }

    // 提交任务到线程池
    public void executeTask(Runnable task) {
        threadPoolExecutor.execute(task);
    }

    // 提交任务并获取结果
    public <T> Future<T> submitTask(Callable<T> task) {
        return threadPoolExecutor.submit(task);
    }

    // 关闭线程池
    public void shutdown() {
        threadPoolExecutor.shutdown();
    }

    // 强制关闭线程池
    public void shutdownNow() {
        threadPoolExecutor.shutdownNow();
    }

    // 获取线程池状态
    public boolean isTerminated() {
        return threadPoolExecutor.isTerminated();
    }

    // 获取线程池当前任务队列长度
    public int getQueueSize() {
        return threadPoolExecutor.getQueue().size();
    }

    // 获取线程池当前活跃线程数
    public int getActiveCount() {
        return threadPoolExecutor.getActiveCount();
    }

    // 获取线程池核心线程数
    public int getCorePoolSize() {
        return threadPoolExecutor.getCorePoolSize();
    }

    // 设置线程池核心线程数
    public void setCorePoolSize(int corePoolSize) {
        threadPoolExecutor.setCorePoolSize(corePoolSize);
    }

    // 获取线程池最大线程数
    public int getMaximumPoolSize() {
        return threadPoolExecutor.getMaximumPoolSize();
    }

    // 设置线程池最大线程数
    public void setMaximumPoolSize(int maximumPoolSize) {
        threadPoolExecutor.setMaximumPoolSize(maximumPoolSize);
    }

    // 获取线程池是否已关闭
    public boolean isShutdown() {
        return threadPoolExecutor.isShutdown();
    }
}
